#!/usr/bin/env python3
"""1688爬虫使用示例"""

from crawler.spider import Product1688Spider
from crawler.utils import save_to_json, save_to_csv, print_product_summary
from config.settings import Settings


def basic_example():
    """基础使用示例"""
    print("=== 基础使用示例 ===")
    
    # 创建爬虫实例
    spider = Product1688Spider(headless=True)
    
    try:
        # 搜索商品
        result = spider.search_products(
            keyword="手机壳",
            max_pages=2,
            sort_by_sales=True,
            filter_guangzhou=True
        )
        
        print(f"搜索关键词: {result.keyword}")
        print(f"找到商品数量: {result.total_count}")
        
        # 显示前5个商品
        for i, product in enumerate(result.products[:5], 1):
            print(f"\n{i}. {product.title}")
            print(f"   价格: {product.price}")
            print(f"   销量: {product.sales}")
            print(f"   发货地: {product.location}")
            print(f"   链接: {product.product_url}")
        
        # 保存结果
        Settings.create_output_dir()
        save_to_json(result, "output/example_results.json")
        save_to_csv(result.products, "output/example_results.csv")
        
        print("\n结果已保存到 output/ 目录")
        
    except Exception as e:
        print(f"搜索过程中出错: {e}")


def advanced_example():
    """高级使用示例"""
    print("\n=== 高级使用示例 ===")
    
    # 使用上下文管理器
    with Product1688Spider(headless=True) as spider:
        # 搜索多个关键词
        keywords = ["数据线", "充电器"]
        
        for keyword in keywords:
            print(f"\n正在搜索: {keyword}")
            
            result = spider.search_products(
                keyword=keyword,
                max_pages=1,
                sort_by_sales=True,
                filter_guangzhou=True
            )
            
            print(f"找到 {result.total_count} 个商品")
            
            if result.products:
                # 显示销量最高的商品
                top_product = result.products[0]
                print(f"销量最高: {top_product.title}")
                print(f"销量: {top_product.sales}")
                print(f"价格: {top_product.price}")


def filter_example():
    """筛选示例"""
    print("\n=== 筛选示例 ===")
    
    with Product1688Spider(headless=True) as spider:
        # 不筛选广州，获取所有地区的商品
        result_all = spider.search_products(
            keyword="蓝牙耳机",
            max_pages=1,
            sort_by_sales=True,
            filter_guangzhou=False
        )
        
        print(f"所有地区商品数量: {result_all.total_count}")
        
        # 只筛选广州发货的商品
        result_gz = spider.search_products(
            keyword="蓝牙耳机",
            max_pages=1,
            sort_by_sales=True,
            filter_guangzhou=True
        )
        
        print(f"广州发货商品数量: {result_gz.total_count}")
        
        # 显示地区分布
        if result_all.products:
            locations = {}
            for product in result_all.products:
                location = product.location or "未知"
                locations[location] = locations.get(location, 0) + 1
            
            print("\n发货地分布:")
            for location, count in sorted(locations.items(), key=lambda x: x[1], reverse=True):
                print(f"  {location}: {count} 个商品")


def main():
    """主函数"""
    print("1688商品搜索爬虫使用示例")
    print("=" * 50)
    
    try:
        # 运行示例
        basic_example()
        advanced_example()
        filter_example()
        
        print("\n=== 所有示例运行完成 ===")
        
    except KeyboardInterrupt:
        print("\n用户中断操作")
    except Exception as e:
        print(f"\n运行示例时出错: {e}")


if __name__ == "__main__":
    main()